package com.geek.factory.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.geek.factory.mapper.OrderContractMapper;
import com.geek.factory.entity.Orders;
import com.geek.factory.entity.OrderContract;
import com.geek.factory.mapper.OrdersMapper;
import com.geek.factory.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-06-19
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private OrderContractMapper orderContractMapper;
    //添加检查组
    @Transactional
    @Override
    public boolean save(Integer[] tContractIds, Orders orders) {
        //1.先插入检查组
        int i = baseMapper.insert(orders);
        //2.再插入关系表
        insertTOrderContract(tContractIds , orders);
        return i>0?true:false;
    }

    //再插入关系表
    private void insertTOrderContract(Integer[] tContractIds, Orders orders) {
        // 添加空值检查
        if (tContractIds == null || tContractIds.length == 0) {
            return;
        }
        Stream.of(tContractIds).forEach(contractId -> {
            OrderContract orderContract = new OrderContract();
            orderContract.setContractId(contractId);
            orderContract.setOrderId(orders.getId());
            orderContractMapper.insert(orderContract);
        });
    }
    @Transactional
    @Override
    public boolean updateOrderWithContracts(Orders orders, Integer[] contractIds) {
        // 1. 更新订单基本信息
        boolean updateOrder = this.updateById(orders);

        // 2. 删除原有合同关联
        LambdaQueryWrapper<OrderContract> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderContract::getOrderId, orders.getId());
        orderContractMapper.delete(wrapper);

        // 3. 添加新的合同关联
        if (contractIds != null && contractIds.length > 0) {
            insertTOrderContract(contractIds, orders);
        }

        return updateOrder;
    }

    @Override
    public List<Integer> findContractIdsByOrderId(Long orderId) {
        LambdaQueryWrapper<OrderContract> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderContract::getOrderId, orderId);
        wrapper.select(OrderContract::getContractId);

        return orderContractMapper.selectList(wrapper)
                .stream()
                .map(OrderContract::getContractId)
                .collect(Collectors.toList());
    }


//    大屏

// ============ 大屏数据统计方法 ============

    /**
     * 获取订单状态分布
     */
    public Map<String, Long> getOrderStatusDistribution() {
        List<Map<String, Object>> result = baseMapper.selectMaps(
                new QueryWrapper<Orders>()
                        .select("order_status as status", "COUNT(*) as count")
                        .groupBy("order_status")
        );

        Map<String, Long> distribution = new HashMap<>();
        result.forEach(map -> {
            String status = "status_" + map.get("status");
            Long count = (Long) map.get("count");
            distribution.put(status, count);
        });
        return distribution;
    }

    /**
     * 获取订单时间序列数据
     * @param start 开始时间
     * @param end 结束时间
     * @param groupBy 分组方式 (day/hour)
     */
    public List<Map<String, Object>> getOrderTimeSeries(LocalDateTime start, LocalDateTime end, String groupBy) {
        String dateFormat = "hour".equals(groupBy) ? "%Y-%m-%d %H:00:00" : "%Y-%m-%d";

        return baseMapper.selectMaps(
                new QueryWrapper<Orders>()
                        .select("DATE_FORMAT(order_date, '" + dateFormat + "') as time",
                                "COUNT(*) as count",
                                "SUM(amount) as totalAmount")
                        .between("order_date", start, end)
                        .groupBy("time")
                        .orderByAsc("time")
        );
    }

    /**
     * 获取金额统计数据
     */
    public Map<String, BigDecimal> getAmountStatistics() {
        Map<String, Object> result = baseMapper.selectMaps(
                new QueryWrapper<Orders>()
                        .select("SUM(amount) as total",
                                "AVG(amount) as average",
                                "MAX(amount) as max",
                                "MIN(amount) as min")
        ).get(0);

        Map<String, BigDecimal> stats = new HashMap<>();
        stats.put("total", (BigDecimal) result.get("total"));
        stats.put("average", (BigDecimal) result.get("average"));
        stats.put("max", (BigDecimal) result.get("max"));
        stats.put("min", (BigDecimal) result.get("min"));

        return stats;
    }

    /**
     * 获取订单金额趋势（按状态分组）
     */
    public List<Map<String, Object>> getAmountTrendByStatus(LocalDateTime start, LocalDateTime end) {
        return baseMapper.selectMaps(
                new QueryWrapper<Orders>()
                        .select("DATE_FORMAT(order_date, '%Y-%m-%d') as date",
                                "order_status as status",
                                "SUM(amount) as totalAmount")
                        .between("order_date", start, end)
                        .groupBy("date", "status")
                        .orderByAsc("date")
        );
    }


    @Override
    public Map<String, Object> getUninvoicedOrderReminders() {
        Map<String, Object> result = new HashMap<>();

        // 1. 获取未开票订单总数
        long totalCount = this.count(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getIsInvoiced, false));
        result.put("uninvoicedCount", totalCount);

        // 2. 获取最近5个未开票订单（用于提醒）
        List<Orders> recentOrders = this.list(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getIsInvoiced, false)
                .orderByDesc(Orders::getOrderDate)
                .last("LIMIT 5"));
        result.put("recentUninvoicedOrders", recentOrders);

        // 3. 获取最旧的未开票订单（用于提醒）
        Orders oldestUninvoiced = this.getOne(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getIsInvoiced, false)
                .orderByAsc(Orders::getOrderDate)
                .last("LIMIT 1"));
        result.put("oldestUninvoicedOrder", oldestUninvoiced);

        return result;
    }

}
